package com.vertxExample.starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

/**
 * 获取路由参数
 * @author Admin
 */
public class BodyVerticle extends AbstractVerticle {
	// create object router
	Router router;


	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		// set router
		Router router = Router.router(vertx);
		// 要想获得body参数，必须添加这句话
		router.route().handler(BodyHandler.create());



		// formData格式
		// 请求头中 content-type :"application/x-www.form-urlencoded"
		router.route("/test/form").handler(req -> {
			// 获取formData格式参数
			var page = req.request().getFormAttribute("page");

			var name = req.request().getFormAttribute("name");

			req.response()
				.putHeader("content-type", "application/json")
				.end(
					new JsonObject().put("hello", "Hello from Vert.x!")
						.put("page", page)
						.put("name", name)
					.toString());
		});
		// json 格式
		// 请求头中 content-type:"application/json"
		router.route("/test/json").handler(req -> {
			// vert 获取json格式数据
			var page = req.getBodyAsJson();
			System.out.println(page);
			req.response()
				.putHeader("content-type", "application/json")
				.end(
					new JsonObject().put("hello", "Hello from Vert.x!")
					.put("page", page.toString())
					.toString()
				);
		});

		// start web
		vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
			if (http.succeeded()) {
				startPromise.complete();
				System.out.println("HTTP server started on port 8888");
			} else {
				startPromise.fail(http.cause());
			}
		});
	}
}
